import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController } from 'ionic-angular';
import { GLAPI } from '../../app/GLAPI.service';
import { GLBookChapter } from '../../app/GLBookChapter';
import { ListPage } from '../list/list';
import { GLFolder } from '../../app/GLFolder';

/*
  Generated class for the Chapter page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-chapter',
  templateUrl: 'chapter.html'
})
export class ChapterPage {

  public item: GLBookChapter;

  public footnotes: boolean;

  private catalog: GLFolder;
  private verse: string;

  private cachedContent: string;

  private paragraphs: boolean = !!localStorage["paragraphs"];

  constructor(public navCtrl: NavController, public navParams: NavParams, glAPI: GLAPI, private loadingCtl: LoadingController) {
    window["CHAPTER_PAGE"] = this;

    this.verse = navParams.data.verse;
    if (this.verse && this.verse[0] === '#') {
      this.verse = this.verse.substr(1);
      this.footnotes = true;
    }

    glAPI.getCatalog().then((catalog) => {
      this.catalog = catalog;
      this.item = <GLBookChapter>catalog.getChildByID(navParams.data.itemID);
    })
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ChapterPage');
  }

  handleClick(event) {
    console.log(event);
    event.preventDefault();
    if (event.target.tagName == 'A') {
      console.log(event.target);
      let hash = event.target.hash;
      if (hash) {
        console.log("There is a hash");
        ListPage.open(this.item, this.navCtrl, hash);
      }
      else {
        var path = event.target.pathname;
        if (path) {
          if (path[0] != '/') {
            path = '/' + path;
          }
          let ind = path.lastIndexOf('.');
          var verse;
          if (ind > -1) {
            verse = path.substring(ind + 1);
            path = path.substring(0, ind);
          }
          console.log(path);
          let loading = this.loadingCtl.create();
          loading.present();
          this.catalog.getChildDeep(path).then((page) => {
            loading.dismiss();
            if (page) {
              ListPage.open(page, this.navCtrl, verse);
            }
          });
        }
      }
    }
  }

  transform(content: string) {
    if (!content) {
      return content;
    }
    else {
      if (!this.cachedContent) {
        this.cachedContent = this.realTransform(content);
      }
      return this.cachedContent;
    }
  }

  realTransform(content: string) {
    if (!content) {
      return content;
    }
    let verses: string[] = [].concat.apply([], (this.verse || "").split(",").map((verse) => {
      let ind = verse.indexOf("-");
      if (ind < 0) {
        return [verse];
      }
      else {
        let start = parseInt(verse.substr(0, ind));
        let end = parseInt(verse.substr(ind + 1));
        let tr = [];
        for (var i = start; i <= end; i++) {
          tr.push(i.toString());
        }
        return tr;
      }
    }));
    console.log(verses);
    let newDom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', "html", null);
    let newBody = newDom.createElementNS('http://www.w3.org/1999/xhtml', 'body');
    newDom.documentElement.appendChild(newBody);
    console.log("bloop");
    let dom = new DOMParser().parseFromString(content, 'text/html');
    let children = dom.body.children;
    console.log(dom.body);
    console.log("children", children);
    var i = 0;
    while(children.length > i) {
      let child = children[i];
      console.log("child", child);
      if(child.className != "bodyBlock") {
        newBody.appendChild(child);
      }
      else {
        var newDiv = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        var para;
        var divs = child.children;
        console.log(divs);
        var j = 0;
        while(divs.length > j) {
          var div = divs[j];
          console.log(div);
          if(!para || div.textContent.indexOf("\u00b6") > -1) {
            para = document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
            para.className = "paragraph";
            newDiv.appendChild(para);
          }
          if (verses.indexOf(div.id) > -1) {
            div.className += " selected";
          }
          para.appendChild(div);
        }
        newBody.appendChild(newDiv);
        i++; 
        console.log(newDiv);
      }
    }
    setTimeout(() => {
      let selecteds = document.getElementsByClassName('selected');
      console.log(selecteds);
      if (selecteds.length >= verses.length && verses.length > 0) {
        let elem = selecteds[selecteds.length - verses.length];
        console.log("scrolling to:");
        console.log(elem);
        // this doesn't work for some reason:
        /*let rect = elem.getBoundingClientRect();
        let top = rect.top + window.pageYOffset;
        let dest = top - window.innerHeight / 4;
        console.log("meaning " + dest);
        window.scrollTo(0, dest);*/

        (<any>elem).scrollIntoView();
      }
    }, 100);
    return newBody.innerHTML;
  }

}
